<?php

namespace IDock\Insurance\ACIC\Request;

use IDock\Http\Request;
use IDock\Http\RequestFormat;
use IDock\Http\RequestMethod;
use IDock\Http\Response;
use SoapClient;
use SoapHeader;

class AllACICRequest extends Request
{

    protected $code;

    protected $method = RequestMethod::POST;

    protected $format = RequestFormat::FORM;

    protected $EChannelId = '';

    public $gateway;

    public $noCarApi = false;

    public function loadConfig(array $config): Request
    {
        $this->gateway = $config['gateway'] ?? '';

        $this->logsDir = $config['logsDir'] ?? '';

        $this->timeout = $config['timeout'] ?? '';

        $this->proxy = $config['proxy'];

        $this->proxyPW = $config['proxyPW'] ?? '';

        $this->proxyAccount = $config['proxyAccount'] ?? '';

        return $this;
    }

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    public function request(Request $request,Response $multiplexResponse = null): Response
    {
        return $this->soapRequest($request, $this->noCarApi ? 'echannelRequest': 'vchlRequest',$multiplexResponse);
    }

    public function payRequest(Request $request): Response
    {
        return parent::request($request);
    }

    public function setEChannelId(string $EChannelId)
    {
        $this->EChannelId = $EChannelId;
    }

    public function soapRequest(Request $request,$route,Response $multiplexResponse = null)
    {
        $this->bindSoapOptions();

        $this->mkLogsDir();

        $request->requestLogs($request->requestId,$request->inLog);

        if (!$multiplexResponse) {
            $response = $request->getResponse();

            $response = new $response;
        } else {
            $response = $multiplexResponse;
        }
        //-----
        //-----
        //测试
        if ($GLOBALS['testResponse'] ?? '') {
            $string = $GLOBALS['testResponse'];
            $response->setBody($string);
            $response->setCode('200');
            $response->resolve();
            return $response;
        }
        //------
        //------

        //接口请求
        try {
            libxml_disable_entity_loader(false);
            $client = new SoapClient($request->gateway, $this->option);

            $body = $client->__soapCall($route, $request->bizParam);

            $this->responseLogs($this->requestId, $body);

            $response->setCode(200)
                ->setBody($body)
                ->resolve();
            return $response;
        } catch (\Exception $e) {
            $this->responseLogs($this->requestId, $e->getMessage());
            $response->setCode('500')
                ->setError($e->getMessage());
            return $response;
        }
    }

}
